package com.rockcent.mall.lib.repository;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.common.SQLListDoing;
import com.rockcent.mall.lib.domain.Topic;
import com.rockcent.mall.lib.domain.TopicProduct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by zhangjh on 2016/11/18.
 */
@Component
public class TopicProductRepositoryImpl implements TopicProductRepositoryCustom {
    private static final Logger log = LoggerFactory.getLogger(TopicProductRepositoryImpl.class);

    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public List<TopicProduct> findAllByTopicId(Long topicId) {

        SQLListDoing doing = (sql, fields, params, typeReferenceMap) -> {
            sql.append("SELECT %s FROM topic_product p left join product pp on p.product_id = pp.id WHERE 1=1 ");
            fields.append("p.*,pp.name");

            //主题标题
            if (null != topicId) {
                sql.append(" AND p.topic_id LIKE :topicId");
                params.put("topicId", topicId);
            }

            sql.append(" order by seq_no asc,date_created desc ");
            log.debug(sql.toString());
        };
        return doing.go(TopicProduct.class, objectMapper, jdbcTemplate, log);
    }

    @Override
    public List<Topic> findAllTopicByProductId(Long productId) {
        SQLListDoing doing = (sql, fields, params, typeReferenceMap) -> {
            sql.append("SELECT %s from topic t left join topic_product p on t.id = p.topic_id    ");
            fields.append("DISTINCT t.*");

            if (null != productId) {
                sql.append(" where  p.product_id = :productId");
                params.put("productId", productId);
            }
        };
        return doing.go(Topic.class, objectMapper, jdbcTemplate, log);
    }

}
